import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, getInfo, logout, refreshTokens } from '@/api/login'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '@/store/mutation-types'
import { welcome, parseJWT } from '@/utils/util'

storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    // {
    // "code": 0,
    // "msg": "ok",
    // "data": {
    //     "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VySWQiOjIsInVzZXJJZGVudGl0eU5hbWVzIjpbXSwibmlja25hbWUiOm51bGwsImV4cGlyZWRUaW1lIjoxNzUzMzI0NjgzODMyfQ.PcOGx5oA0MgV1ZB631XSJP43R1X1tjxFZQDvafZbAVpGf0uqHE4w0RCeSap46iwF1My7vf_cRuZIgOvXuSI5pVu3vsHFzuAwfi-kTYQr8tTJgB1-DmLBRSGu8I6prn0c12spaOM2h8kFJMvBtKWCfvsrmNo-pE63MSh-PJT49YXZFoMKp5t9PMwmmdquq0X48hDedpzv27jEhpMgSpb_j7iXla2DuzcWff9rwdmkOFyFFOlne8L9DahO7stVr8qftCZrVvgJ56H-zH4gUzqUhfBrDUkKIWKjKJAnpS6f_S1EXoTl7-8axebIHtNbj3l0XOb44Ej2auMilQ4Zs4nJZg",
    //     "tokenHead": "Bearer ",
    //     "tokenExpiredTime": 1753324683832,
    //     "refreshToken": "t02JJhfsp7cptCtPsFfHyX12BLi4BLYvcOijiIfmdPX8KzruIjYHChcU1ZdfIBCjDxlShMRoA2VPVVmy0UehO5oQDAlGUpk60XO0uekNxTAFANIO5g9CTCQ7yJBMNTcn"
    // }
    // }
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((response) => {
            const result = response.data
            const accessToken = result.tokenHead + result.token
            const refreshToken = result.refreshToken
            storage.set(ACCESS_TOKEN, accessToken)
            storage.set(REFRESH_TOKEN, refreshToken)
            commit('SET_TOKEN', accessToken)
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo()
          .then((response) => {
            const { result } = response
            if (result.role && result.role.permissions.length > 0) {
              const role = { ...result.role }
              role.permissions = result.role.permissions.map((permission) => {
                const per = {
                  ...permission,
                  actionList: (permission.actionEntitySet || {}).map((item) => item.action)
                }
                return per
              })
              role.permissionList = role.permissions.map((permission) => {
                return permission.permissionId
              })
              // 覆盖响应体的 role, 供下游使用
              result.role = role
              commit('SET_ROLES', role)
              commit('SET_INFO', result)
              commit('SET_NAME', { name: result.name, welcome: welcome() })
              commit('SET_AVATAR', result.avatar)
              try {
                const token = storage.get(ACCESS_TOKEN)
                const decoded = parseJWT(token)
                console.log('decoded', decoded)
              } catch (error) {
                console.log('decoded', error)
              }
              // 下游
              resolve(result)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            storage.remove(ACCESS_TOKEN)
            storage.remove(REFRESH_TOKEN)
            resolve()
          })
          .catch((err) => {
            console.log('logout fail:', err)
            // resolve()
          })
          .finally(() => {})
      })
    },
    exitSystem ({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        storage.remove(ACCESS_TOKEN)
        storage.remove(REFRESH_TOKEN)
        resolve()
      })
    },
    // Refresh token
    RefreshToken ({ commit }) {
      return new Promise((resolve, reject) => {
        const refreshToken = storage.get(REFRESH_TOKEN)
        if (!refreshToken) {
          reject(new Error('No refresh token available'))
          return
        }

        refreshTokens(refreshToken)
          .then((response) => {
            const result = response.data
            if (result) {
              const accessToken = result.tokenHead + result.token
              const newRefreshToken = result.refreshToken
              storage.set(ACCESS_TOKEN, accessToken)
              storage.set(REFRESH_TOKEN, newRefreshToken)
              commit('SET_TOKEN', accessToken)
              resolve(accessToken)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    }
  }
}

export default user
